import {Button, Form, Input, message, Modal, Select, TimePicker} from 'antd';
import React, { Component } from 'react';

import { FormComponentProps } from 'antd/es/form';
import { TableListItem } from '../data.d';
import moment from 'moment';
import { updateCourse, removeCourse ,queryCourse, addCourse,queryClassroom,queryDepartment } from '../service';
import {queryTeacher} from "@/pages/Course/service";
const { Option } = Select;
export interface FormValueType extends Partial<TableListItem> {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
}

export interface UpdateFormProps extends FormComponentProps {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => void;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
}
const FormItem = Form.Item;
const { RangePicker } = TimePicker;
export interface UpdateFormState {
  formVals: FormValueType;
}

class UpdateForm extends Component<UpdateFormProps, UpdateFormState> {
  static defaultProps = {
    handleUpdate: () => {},
    handleUpdateModalVisible: () => {},
    values: {},
  };

  formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };
  formRef = React.createRef();
  constructor(props: UpdateFormProps) {
    super(props);
    let time = props.values.time.split("-");
    console.log(time[0])
    console.log(moment('13:30:56', 'HH:mm:ss'))
    time[0] = moment(time[0],'HH:mm:ss')
    time[1] = moment(time[1],'HH:mm:ss')
    console.log(time)
    this.state = {
      propsItem: {
        id:props.values.key,
        course_name: props.values.course_name,
        people_num: props.values.people_num,
        department_id: props.values.department_id,
        classroom_id: props.values.classroom_id,
        teacher_id: props.values.teacher_id,
        time: time
      }
    };
  }
  componentWillMount = async () => {
    try {
      let classroom = await queryClassroom();
      let department =  await queryDepartment();
      let teacher = await queryTeacher();
      let classroom_option:any = [];
      classroom.data.map((data)=>{
        classroom_option.push(<Select.Option value={data.id} key={data.key}>{data.name}</Select.Option>);
      })
      console.log(department)
      let department_option:any = [];
      department.data.map((data)=>{
        department_option.push(<Select.Option value={data.id} key={data.key}>{data.department_name}</Select.Option>);
      })

      let teacher_option:any = [];
      teacher.data.map((data)=>{
        teacher_option.push(<Select.Option value={data.id} key={data.key}>{data.username}</Select.Option>);
      })
      this.setState({
        classroom : classroom_option,
        department : department_option,
        teacher:teacher_option
      })
    }
    finally {

    }
  }
  handleNext = () => {
    const {form, onSubmit: handleUpdate} = this.props;
    let {validateFields} =  this.formRef.current;
    validateFields().then(values=>{
      console.log(values);
      let time = this.state.time;
      let data = {
        id:this.state.propsItem.id,
        course_name: values.course_name,
        department_id: values.department_id,
        classroom_id: values.classroom_id,
        people_num: values.people_num,
        time: `${time[0]}-${time[1]}`,
        teacher_id:values.teacher_id
      }
      console.log(data);
      if(!data.teacher_id){
        message.error("请选择教师");
        return;
      }
      if(data.course_name == undefined || data.department_id == undefined || data.department_id == undefined
        || data.classroom_id == undefined || data.people_num == undefined){
        message.error("请填写所有信息");
        return;
      }
      console.log(data);
      handleUpdate(data);
    })
  };



  renderFooter = () => {
    const { onCancel: handleUpdateModalVisible, values } = this.props;
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext()}>
        完成
      </Button>,
    ];
  };

  render() {
    const { updateModalVisible, onCancel: handleUpdateModalVisible, values ,modalVisible, form, onSubmit: handleAdd, onCancel} = this.props;
    const {  formVals } = this.state;
    const {Option} = Select;
    const format = 'HH:mm';
    const FormItem = Form.Item;
    function handleChange(value){
      console.log(`selected ${value}`);
    }

    function onChange(value) {
      console.log(`selected ${value}`);
    }

    function onBlur() {
      console.log('blur');
    }

    function onFocus() {
      console.log('focus');
    }

    function onSearch(val) {
      console.log('search:', val);
    }
    const onTimeChange = (value, dateString) =>{
      console.log('Selected Time: ', value);
      console.log('Formatted Selected Time: ', dateString);
      this.setState({
        time : dateString
      })
    }
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="课程修改"
        visible={updateModalVisible}
        footer={this.renderFooter()}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
      >
        <Form
          ref={this.formRef}
          initialValues={this.state.propsItem}
        >
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="课程名称"
          name="course_name"
          rules={[{ required: true }]}
        >
         <Input placeholder="请输入课程名称"/>
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="系部名称"
          name="department_id"
        >
            {/*initialValue: formVals.course_name,*/}
          <Select
            showSearch
            style={{width: 200}}
            placeholder="Select a person"
            optionFilterProp="children"
            onChange={onChange}
            onFocus={onFocus}
            onBlur={onBlur}
            onSearch={onSearch}
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {this.state.department}
          </Select>
        </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="请选择教室"
          name="classroom_id"
        >
            {/*initialValue: this.state.classroom[0],*/}
          <Select
            showSearch
            style={{width: 200}}
            placeholder="Select a person"
            optionFilterProp="children"
            onChange={onChange}
            onFocus={onFocus}
            onBlur={onBlur}
            onSearch={onSearch}
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {this.state.classroom}
          </Select>
        </FormItem>
          <FormItem
            labelCol={{
              span: 5,
            }}
            wrapperCol={{
              span: 15,
            }}
            label="请选择教师"
            name="teacher_id"
          >
            <Select
              showSearch
              style={{width: 200}}
              placeholder="Select a person"
              optionFilterProp="children"
              onChange={onChange}
              onFocus={onFocus}
              onBlur={onBlur}
              onSearch={onSearch}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {this.state.teacher}
            </Select>
          </FormItem>
          <FormItem
            labelCol={{
              span: 5,
            }}
            wrapperCol={{
              span: 15,
            }}
            label="选择上课时间"
            name="time"
          >
            <RangePicker onChange={onTimeChange}/>
          </FormItem>
        <FormItem
          labelCol={{
            span: 5,
          }}
          wrapperCol={{
            span: 15,
          }}
          label="选择上课人数"
          name="people_num"
        >
          {/*initialValue: formVals.people_num,*/}
          <Input placeholder="请输入人数" type='number'/>
        </FormItem>
        </Form>
      </Modal>
    );
  }
}

export default UpdateForm;
